package edu.hunan.cxb18.controller;

import edu.hunan.cxb18.car.Car;
import edu.hunan.cxb18.pojo.Product;
import edu.hunan.cxb18.result.CommonTypeResult;
import edu.hunan.cxb18.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author AuthorName
 * @create 2020-04-26 9:36
 */
@RestController
@RequestMapping("/car")
public class CarController {
    @Autowired
    private ProductService productService;
    @RequestMapping("/add")
    public CommonTypeResult add(HttpServletRequest request, @RequestParam(name = "id") int id, @RequestParam(name = "qty") int qty){
        HttpSession session = request.getSession();
        Car car = (Car)session.getAttribute("car");
        if (car==null){
            car = new Car();
            session.setAttribute("car", car);
        }
        Product product = productService.queryById(id);
        car.add(product,qty);
        return CommonTypeResult.creat(null);
    }
    @RequestMapping("/load")
    public CommonTypeResult load(HttpServletRequest request){
        HttpSession session = request.getSession();
        Car car = (Car)session.getAttribute("car");
        if (car==null){
            return CommonTypeResult.creat(car,"false");
        }
        return CommonTypeResult.creat(car);
    }
    @RequestMapping("/delete")
    public CommonTypeResult delete(HttpServletRequest request, @RequestParam(name = "id") int id){
        HttpSession session = request.getSession();
        Car car = (Car)session.getAttribute("car");
        if (car==null){
            return CommonTypeResult.creat(car,"false");
        }else {
            car.delete(id);
            return CommonTypeResult.creat(car,"success");
        }
    }
    @RequestMapping("/modify")
    public CommonTypeResult modify(HttpServletRequest request, @RequestParam(name = "id") int id, @RequestParam(name = "qty") int qty){
        HttpSession session = request.getSession();
        Car car = (Car)session.getAttribute("car");
        if (car==null){
            return CommonTypeResult.creat(car,"false");
        }else {
            car.modify(id,qty);
            return CommonTypeResult.creat(car,"success");
        }
    }
    @RequestMapping("/deleteall")
    public CommonTypeResult delete(HttpServletRequest request){
        HttpSession session = request.getSession();
        Car car = (Car)session.getAttribute("car");
        if (car==null){
            return CommonTypeResult.creat(car,"false");
        }else {
            car.deleteAll();
            return CommonTypeResult.creat(car,"success");
        }
    }
}
